<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/16
 * Time: 10:51
 */

namespace app\controller;
use app\domain\car;
use rap\web\Request;

class JvheController
{

    private $cityUrl = 'http://v.juhe.cn/wz/citys';

    private $wzUrl = 'http://v.juhe.cn/wz/query';

    private $appkey;

    public function __construct($appkey){
        $this->appkey = 'baab909d83975bb5e5dee41076b3f164';
    }

    /**
     * 获取可以查询违章的城市
     * @param Request $request
     */
    public function getCitys (Request $request) {
//        if ($request->method() == "POST") {
            $params = 'key='.$this->appkey."&format=2";
            $content = self::juhecurl($this->cityUrl,$params);
            $data = json_decode($content);

            $result = $data->result;
            $data1 = array();
            $k = 0;
            for ($i = 0; $i < count($result); $i++) {
                $data = $result[$i]->citys;
                for ($j = 0; $j < count($data); $j++) {
                    $data1[$k++] = (array)$data[$j];
                    $res = car::addCarCityInfos((array)$data[$j]);
                }
            }

            die();
            return self::_returnArray($content);
//        }
    }

    public function getWZInfo($car_code, $engine_code, $class_code) {

    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

    /**
     * 将JSON内容转为数据，并返回
     * @param string $content [内容]
     * @return array
     */
    public function _returnArray($content){
        return json_decode($content,true);
    }

}